﻿using System.Collections.Generic;
using System.Web.Mvc;
using Web7.Core.InversionOfControl;
using Web7.Mvc.ViewEngines;
using Web7.Ioc;

//using Web7.Ioc;

namespace Web7.Core.ViewResolvers
{
    /// <summary>
    /// 视图解析器注册表
    /// </summary>
    public class ViewResolverRegistry : IViewResolverRegistry
    {
        private readonly IDependencyInjector _dependencyInjector;
        private readonly Web7Context _context;
        private readonly ViewEngineCollection _viewEngines;
        private readonly List<IViewResolver> _viewResolvers;

        public ViewResolverRegistry(IDependencyInjector dependencyInjector, Web7Context context, ViewEngineCollection viewEngines)
        {
            this._dependencyInjector = dependencyInjector;
            this._context = context;
            this._viewEngines = viewEngines;
            this._viewResolvers = new List<IViewResolver>(5);
        }

        #region IViewResolverRegistry Members

        /// <summary>
        /// 默认视图解析器
        /// </summary>
        public IViewResolver Default { get; set; }

        /// <summary>
        /// 添加视图解析器
        /// </summary>
        /// <param name="viewResolver"></param>
        public void Add(IViewResolver viewResolver)
        {
            _viewResolvers.Add(viewResolver);
        }

        /// <summary>
        /// 生成视图引擎
        /// </summary>
        /// <param name="viewResolverContext"></param>
        /// <returns></returns>
        public IEnumerable<IWeb7ViewEngine> GenerateViewEngines(ViewResolverContext viewResolverContext)
        {
            // newViewEngines用于保存生成的视图引擎集合
            List<IWeb7ViewEngine> newViewEngines = new List<IWeb7ViewEngine>();
            // viewRootPaths用于保存视图解析器生成的路径信息
            List<string> viewRootPaths = new List<string>();

            // 虚拟根目录
            viewRootPaths.Add("~/");

            if (Default != null)
                Default.Resolve(viewResolverContext, viewRootPaths);

            foreach (IViewResolver viewResolver in _viewResolvers)
                viewResolver.Resolve(viewResolverContext, viewRootPaths);

            if (viewRootPaths.Count > 0)
            {
                viewRootPaths.Reverse();

                foreach (string viewRootPath in viewRootPaths)
                {
                    foreach (IViewEngine viewEngine in _viewEngines)
                    {
                        if (viewEngine is IWeb7ViewEngine)
                        {
                            IWeb7ViewEngine viewEngineInstance = (IWeb7ViewEngine)_dependencyInjector.GetService(viewEngine.GetType());

                            viewEngineInstance.RootPath = viewRootPath;

                            newViewEngines.Add(viewEngineInstance);
                        }
                    }
                }
            }

            return newViewEngines;
        }

        #endregion

    }
}
